<template>
    <div>
        <div class="search">
            <input v-model="keywords" class="search-input" placeholder="输入城市名或拼音"/>
        </div>
        <!--下行不能使用 v-if 否则BScroll报错-->
        <div v-show="keywords" class="search-items">
            <ul>
                <li v-for="item of list" class="search-item border-bottom"
                    @click="handleCityClick(item)"
                >{{item}}</li>
                <li v-if="!list.length" class="search-item border-bottom">没有找到匹配项</li>
            </ul>
        </div>
    </div>
</template>

<script>
    import BScroll from 'better-scroll'
    export default {
        name: "search",
        props:{
            cities:Object
        },
        data(){
            return{
                keywords:'',
                list: []
            }
        },
        watch:{
            keywords(){
                if(this.searchTimer){
                    clearTimeout(this.searchTimer)
                }
                this.searchTimer=setTimeout(()=>{
                    var arr=[]
                    for(var k in this.cities){
                        for(var i in this.cities[k]){
                            var tar=this.cities[k][i]
                            if(tar.spell.indexOf(this.keywords)>-1 || tar.name.indexOf(this.keywords)>-1)
                                arr.push(tar.name)
                        }
                    }
                    this.list=arr;
                }, 300)
            }
        },
        mounted(){
            new BScroll('.search-items', {click: true})
        },
        methods:{
            handleCityClick(city){
                this.$store.dispatch('changeCity', city)
                this.$router.push('/')
            }
        }
    }
</script>

<style scoped lang="stylus">
    @import "~@styles/variables.styl"
    .border-bottom
        &:before
            border-color:#ccc
    .search
        background-color: $bgColor_head
        padding: 0 .1rem
        height: $lineHeight*0.9
        .search-input
            box-sizing: border-box
            width: 100%
            color: $darkTextColor
            padding: 0 .1rem
            height: $lineHeight*0.85
    .search-items
        z-index: 1
        background-color: $bgColor_dark
        position: absolute
        overflow:hidden /*消除上滚问题*/
        bottom:0
        top: $lineHeight*1.9
        left:0
        right:0
        .search-item
            background-color: white
            height: $lineHeight*0.85
            line-height: $lineHeight*0.85
            padding: 0 .2rem
</style>